package com.itheima.health.security;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.health.pojo.Permission;
import com.itheima.health.pojo.Role;
import com.itheima.health.pojo.User;
import com.itheima.health.service.UserService;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import java.util.ArrayList;
import java.util.Collection;

public class SecurityUserDetailsService implements UserDetailsService {

    @Reference
    private UserService userService;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //RPC获取用户数据
        User user = userService.findByUsername(username);
        if (null==user){
            throw new UsernameNotFoundException("用户"+username+"不存在");
        }
        String userName = user.getUsername();
        String password = user.getPassword();

        //获取用户角色及权限
        Collection<GrantedAuthority> authList = new ArrayList<>();
        //角色关键字
        for (Role role : user.getRoles()) {
            authList.add(new SimpleGrantedAuthority(role.getKeyword()));
            //权限关键字
            for (Permission permission : role.getPermissions()) {
                authList.add(new SimpleGrantedAuthority(permission.getKeyword()));
            }
        }
        return new org.springframework.security.core.userdetails.User(userName,password,authList);
    }
}
